﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using bus_TienichNPC;
using BaocaoNPC.common;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for IN_DS_KHANG_DIENBIEN.xaml
    /// </summary>
    public partial class IN_DS_KHANG_DIENBIEN : UserControl
    {
        #region Khai bao
        CN_THEODOINO_bus THEODOINO_bus = new CN_THEODOINO_bus();
        public String strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strUsername = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public String strMa_TNgan = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap.ToUpper() : "PA";
        DataSet dsResult = new DataSet();
        DataSet dsTrung = new DataSet();
        DataSet ds_ketqua = new DataSet();
        DataSet ds_cn = new BCNPCEntities.EXCEL.ds_CN();
        #endregion

        public IN_DS_KHANG_DIENBIEN()
        {
            InitializeComponent();
            LOAD_DATA();
        }

        private void LOAD_DATA()
        {
            try
            {
                DataSet ds_TNV = new DataSet();
                ds_TNV = GlobalServices.Service_NPCUS.SELECT_ALL_THONGTIN_KHANG(strMa_dviqly);
                //ds_TNV = THEODOINO_bus.SELECT_ALL_THONGTIN_KHANG(strMa_dviqly);
                if (ds_TNV == null) return;
                fill_dulieu(ds_TNV);
            }
            catch (Exception ex)
            { }
        }

        private void fill_dulieu(DataSet ds)
        {
            try
            {
                if (ds.Tables[0].Rows.Count == 0) return;
                if (ds == null) return;
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();

                if (trvBBAN != null) trvBBAN.Items.Clear();
                DataView dv = new DataView(ds.Tables[0]);
                dv.Sort = "MA_TNGAN";
                if (dv.Count == 0)
                {
                    superNode.Header = "Không có dữ liệu TNV";
                    superNode.Tag = "Không có dữ liệu TNV@";
                    trvBBAN.Items.Add(superNode);
                    return;
                }
                CheckBox chkSuperNode = new CheckBox();
                chkSuperNode.Content = strTen_dviqly;
                chkSuperNode.Tag = "NUTGOC" + "@" + "" + "@" + "" + "@" + "" + "@" + "";
                chkSuperNode.ToolTip = strTen_dviqly;
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                //trvBBAN.Items.Add(superNode);
                string strnutcha = "";
                string strNutCon = "";
                string str_thungan = "";
                string str_ma_thungan = "";
                foreach (DataRowView dr in dv)
                {
                    str_ma_thungan = dr["MA_TNGAN"].ToString();
                    str_thungan = dr["TEN_TNGAN"].ToString();
                    #region "parentnode"
                    if (str_thungan != strnutcha)
                    {
                        chkNode = new CheckBox();
                        chkNode.Content = str_thungan;
                        chkNode.Tag = str_ma_thungan + "@NUTCHA" + "@" + "" + "@" + "" + "@" + "";
                        chkNode.ToolTip = str_thungan;
                        chkNode.IsChecked = false;
                        chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _node = new TreeViewItem();
                        _node.Header = chkNode;
                        _node.IsExpanded = false;
                        trvBBAN.Items.Add(_node);
                        strnutcha = str_thungan;
                    }
                    # endregion
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        public void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string ma_tngan = strUsername.ToUpper();
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                TreeViewItem itemselect = trvBBAN.SelectedItem as TreeViewItem;
                string[] m = chk.Tag.ToString().Split('@');
                if (chk.IsChecked == true)
                {
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        checkList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (m[1] == "NUTCHA")
                    {
                        dsResult = GlobalServices.Service_NPCUS.SELECT_ALL_THONGTIN_KHANG_TNGAN(strMa_dviqly, m[0]);
                        //dsResult = THEODOINO_bus.SELECT_ALL_THONGTIN_KHANG_TNGAN(strMa_dviqly, m[0]);
                        //dsTrung = THEODOINO_bus.SELECT_HDON_THEOFILE_TRUNG(strMa_dviqly, m[0]);
                        dsTrung = GlobalServices.Service_NPCUS.SELECT_HDON_THEOFILE_TRUNG(strMa_dviqly, m[0]);
                        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                        {
                            if (ds_cn.Tables["GIAO_HDON"].Rows.Count == 0)
                            {
                                copy_dataTable(dsResult.Tables[0], ds_cn.Tables["GIAO_HDON"]);
                                ds_cn.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                            else
                            {
                                for (int i = ds_cn.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_cn.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                                    {
                                        ds_cn.Tables["GIAO_HDON"].Rows[i].Delete();
                                    }
                                }
                                ds_cn.AcceptChanges();
                                copy_dataTable(dsResult.Tables[0], ds_cn.Tables["GIAO_HDON"]);
                                ds_cn.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";
                            }
                        }
                        if (dsTrung != null && dsTrung.Tables[0].Rows.Count > 0)
                        {
                            if (ds_cn.Tables["GIAO_HDON_TRUNG"].Rows.Count == 0)
                            {
                                copy_dataTable_trung(dsTrung.Tables[0], ds_cn.Tables["GIAO_HDON_TRUNG"]);
                                ds_cn.Tables["GIAO_HDON_TRUNG"].DefaultView.RowFilter = "1=1";
                            }
                            else
                            {
                                for (int i = ds_cn.Tables["GIAO_HDON_TRUNG"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_cn.Tables["GIAO_HDON_TRUNG"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                                    {
                                        ds_cn.Tables["GIAO_HDON_TRUNG"].Rows[i].Delete();
                                    }
                                }
                                ds_cn.AcceptChanges();
                                copy_dataTable_trung(dsTrung.Tables[0], ds_cn.Tables["GIAO_HDON_TRUNG"]);
                                ds_cn.Tables["GIAO_HDON_TRUNG"].DefaultView.RowFilter = "1=1";
                            }
                        }
                    }
                }
                else
                {
                    #region Uncheck
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        UncheckList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in trvBBAN.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (m[1].ToString() == "NUTCHA")
                    {
                        for (int i = ds_cn.Tables["GIAO_HDON"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_cn.Tables["GIAO_HDON"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                            {
                                ds_cn.Tables["GIAO_HDON"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_cn.AcceptChanges();
                        ds_cn.Tables["GIAO_HDON"].DefaultView.RowFilter = "1=1";

                        for (int i = ds_cn.Tables["GIAO_HDON_TRUNG"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_cn.Tables["GIAO_HDON_TRUNG"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                            {
                                ds_cn.Tables["GIAO_HDON_TRUNG"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_cn.AcceptChanges();
                        ds_cn.Tables["GIAO_HDON_TRUNG"].DefaultView.RowFilter = "1=1";
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                return;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void copy_dataTable(DataTable dtnguon, DataTable dtDich)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                    dr["TEN_DCHI"] = rgINS[i]["TEN_KHANG"] + "-" + rgINS[i]["DCHI_KHANG"];
                    dr["TIEN"] = rgINS[i]["TIEN_PSINH"];
                    dr["THUE"] = rgINS[i]["THUE_PSINH"];
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["TONG_TIEN"] = rgINS[i]["TONG_TIEN"];
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"];
                    dr["TEN_TNGAN"] = rgINS[i]["TEN_TNGAN"];
                    dr["STT"] = rgINS[i]["STT"];
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"];
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"];
                    dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"];
                    dr["NGAY_GIAO"] = rgINS[i]["NGAY_GIAO"];
                    dr["DV"] = rgINS[i]["HTHUC_TTOAN"];
                    dr["KYTHANGNAM"] = rgINS[i]["KY"] + "-" + rgINS[i]["THANG"] + "/" + rgINS[i]["NAM"];
                    dr["THANG"] = rgINS[i]["THANG"];
                    dr["NAM"] = rgINS[i]["NAM"];
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                }
            }
            catch (Exception ex)
            { }
        }

        private void copy_dataTable_trung(DataTable dtnguon, DataTable dtDich)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"];
                    dr["TEN_TNGAN"] = rgINS[i]["TEN_TNGAN"];
                    dr["STT"] = rgINS[i]["STT"];
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"];
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                }
            }
            catch (Exception ex)
            { }
        }

        private void UncheckList(TreeViewItem nodes, CheckBox chk)
        {
            //dt.Rows.Clear();
            if ((CheckBox)nodes.Header == chk)
            {
                UnCheckAllChildsWhenParentUnCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    UnCheckParent(node);
                    if (node.Items.Count > 0)
                    {
                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = false;
                            if (subNode.Items.Count > 0)
                            {
                                UncheckList(subNode, chkNode);
                            }
                            //load database of childnode
                            //KiemTra_Insert_tbl_All_TheoDoiNo(chkChildNode);
                        }
                    }
                    else
                    {
                        CheckBox chkNode = (CheckBox)node.Header;
                        chkNode.IsChecked = false;
                    }
                }
                else
                {
                    UncheckList(node, chk);
                }

            }
        }

        private void UnCheckParent(TreeViewItem node)
        {
            TreeViewItem parentNode = node.Parent as TreeViewItem;
            if (parentNode != null)
            {
                CheckBox chkParentNode = (CheckBox)parentNode.Header;
                chkParentNode.IsChecked = false;
                UnCheckParent(parentNode);
            }
        }

        private void RefreshCheckBoxList(TreeViewItem nodes)
        {
            DataRow[] dr = null;
            foreach (TreeViewItem subNode in nodes.Items)
            {
                //check all Node
                CheckBox chkNode = (CheckBox)subNode.Header;
                if (subNode.Items.Count > 0)
                {
                    RefreshCheckBoxList(subNode);
                }
                else
                {
                    if (chkNode.IsChecked == true)
                    {

                    }
                    else
                    {

                    }
                }
            }
        }

        private void checkList(TreeViewItem nodes, CheckBox chk)
        {

            if ((CheckBox)nodes.Header == chk)
            {
                CheckAllChildsWhenParentCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    if (node.Items.Count > 0)
                    {

                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = true;
                            if (subNode.Items.Count > 0)
                            {
                                checkList(subNode, chkNode); //chk);
                            }
                        }
                        CheckParentWhenAllChildChecked(nodes);
                    }
                    else
                    {

                        CheckParentWhenAllChildChecked(nodes);
                    }
                }
                else
                {
                    checkList(node, chk);
                }

            }
        }

        private void CheckParentWhenAllChildChecked(TreeViewItem nodes)
        {
            int count = 0;
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                if (chkNode.IsChecked == false)
                {
                    count = count + 1;
                    break;
                }
            }
            if (count == 0)
            {
                CheckBox chkNode = (CheckBox)nodes.Header;
                chkNode.IsChecked = true;
                TreeViewItem parentNode = nodes.Parent as TreeViewItem;
                if (parentNode != null)
                {

                    CheckParentWhenAllChildChecked(parentNode);
                }
            }
        }

        private void CheckAllChildsWhenParentCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = true;
                CheckAllChildsWhenParentCheck(node);
            }
        }

        private void UnCheckAllChildsWhenParentUnCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = false;
                UnCheckAllChildsWhenParentUnCheck(node);
            }
        }

        private void btnIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                string strMatngan = strUsername;
                reports.RP_CHITIET_GIAOHDON_DIENBIEN report = new BaocaoNPC.Usercontrols.reports.RP_CHITIET_GIAOHDON_DIENBIEN();
                report.SetDataSource(ds_cn.Tables["GIAO_HDON"].DefaultView);
                report.SetParameterValue("CONGTY", strTen_dviqly);
                report.SetParameterValue("CONGTYCAPTREN", strTen_dviqly_CT);
                UtilReportOMS.RptManager.showReportToWin(this, report, strMa_dviqly, new string[] { "Formula1", "Formula2", "Formula3" }, new string[] { "Formula1", "Formula2", "Formula3" }, "CMIS2 - Report: Báo cáo NPC");
            }
            catch (Exception ex)
            {
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void btnIN_DS_Trung_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                reports.RP_CHITIET_GIAOHDON_TRUNG report = new BaocaoNPC.Usercontrols.reports.RP_CHITIET_GIAOHDON_TRUNG();
                report.SetDataSource(ds_cn.Tables["GIAO_HDON_TRUNG"].DefaultView);
                report.SetParameterValue("CONGTY", strTen_dviqly);
                report.SetParameterValue("CONGTYCAPTREN", strTen_dviqly_CT);
                UtilReportOMS.RptManager.showReportToWin(this, report, strMa_dviqly, new string[] { "Formula1", "Formula2", "Formula3" }, new string[] { "Formula1", "Formula2", "Formula3" }, "CMIS2 - Report: Báo cáo NPC");
                this.Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            { }
        }
    }
}
